<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Http\Request;
use App\Models\User;

class PasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Create a new password controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'reset']);
    }
    
    public function reset(Request $request) {

        $this->validate($request, [
            'old' => 'required',
            'password' => 'required|confirmed|min:6',
        ]);

        $user_id = $request->user()->user_id;
        $user = User::find($user_id);

        if (!$user) {
            return redirect()->back()->withErrors("用户数据错误");
        }

        if (!password_verify($request->get("old"), $user->password)) {
            return redirect()->back()->withErrors("原密码不匹配");
        }

        $this->resetPassword($user, $request->get("password"));

        return redirect()->back()->withInput(['密码修改成功']);
    }
}
